package com.tool.cn.use.async.core;

/**
 * 
 * @author wangzonghui
 * @date 2022-08-31 04:00:32
 * @Description 异步回调任务控制类，支持成功和异常不同处理模式
 */
public class TaskThread extends Thread{
	
	private TaskIntr taskIntr;
	private int timeOut=0;
	
	/**
	 * 
	 * @param taskIntr 异步回调任务
	 */
	public TaskThread(TaskIntr taskIntr ) {
		this.taskIntr=taskIntr;
	}
	
	/**
	 * 
	 * @param taskIntr 异步回调任务
	 * @param timeOut 超时时间，单位毫秒
	 */
	public TaskThread(TaskIntr taskIntr,int timeOut) {
		this.taskIntr=taskIntr;
		this.timeOut=timeOut;
	}
	
	@Override
	public void run() {
		super.run();
		if(timeOut>0) {
			ProcesscommandTimeout process=new ProcesscommandTimeout();
			int state=process.waitForProcess(timeOut);
			if(state==0) {  //超时
				System.out.println(Thread.currentThread().getName()+"执行超时");
				taskIntr.error();
			
			}else if(state==-1) {  //执行错误
				
				taskIntr.error();
				
			}else {  //未超时
				taskIntr.success();
			}
			
		}else {
			doMask();
		}

	}
	
	private void doMask() {
		try {
			taskIntr.make();
			taskIntr.success();
		} catch (Exception e) {
			taskIntr.error();
			return;
		}
	}

	/**
	 * 
	 * @author wangzonghui
	 * @date 2022-08-31 04:13:08
	 * @Description 异步执行 0 超时 1 未超时 -1 错误
	 */
	class ProcesscommandTimeout extends Thread{
		private int state=0;
		
		public int  waitForProcess(int outtime){
			  this.start();
			  
			  try{
			     this.join(outtime);
			  }catch (InterruptedException e){
				  e.printStackTrace();
				  return -1;
			  }
			  
			  return state;
		 }
		
		@Override
		public void run() {
			super.run();
			taskIntr.make();
			state=1;
		}
	}

}
